import { CustomDataType, MsgTypeMap } from '../constants';

export function getCookie() {
  const arrCookie = document.cookie.split("; ");
  const loginInfo = {};
  for (const c of arrCookie) {
    const arr = c.split("=");
    const [key, val] = arr

    if(key.startsWith('im_')) {
      const configKey = key.split('im_')[1];
      loginInfo[configKey] = val
    }
  }
  console.log('getCookie data>>>', loginInfo);
  return loginInfo;
}

/** 获取search参数 */
export function getLocationSearch(): any {
  const searchStr = window.location.search || window.location.hash;
  if (!searchStr || !searchStr.includes('?')) return {};
  const [, queryStr] = searchStr.split('?');
  if (!queryStr) return {};
  const queryKVList = queryStr.split('&') || [];
  return queryKVList.reduce((acc, cur) => {
    if (cur) {
      const [k, v] = cur.split('=');
      acc[k] = v;
    }
    return acc;
  }, {});
}

export const resolveCustomMsgFormContent = (customerType, content) => {
  switch (customerType) {
    case CustomDataType.UserCard:
      return '[个人名片]';
    case CustomDataType.RichText:
      return '[富文本]';
    default:
      return '';
  }
}

//异步加载函数
export const loadScript = (url, callback?) => {
  const script = document.createElement ("script");
  script.type = "text/javascript";
  script.async = false;
  if ((script as any).readyState){ //IE
    (script as any).onreadystatechange = function(){
        if ((script as any).readyState == "loaded" || (script as any).readyState == "complete"){
          (script as any).onreadystatechange = null;
            if(callback && (typeof callback === 'function')) callback();
        }
      };
  } else { //Others
    script.onload = function(){
      if(callback && (typeof callback === 'function')) callback();
    };
  }
  script.src = url;
  document.getElementsByTagName("head")[0].appendChild(script);
}

export const renderMsgBrief = (messageData) => {
  const { msgType, msgContent: content } = messageData;

  let lastMsg = '';
  switch (msgType?.toLowerCase()) {
    case 'rtc':
      lastMsg = (content && content.rtcAction === 'invite') ? '发起实时音视频邀请' : '收到实时音视频邀请'
      break;
    case 'text':
      lastMsg = content.text || content.m;
      break;
    case 'url':
      lastMsg = `[链接]${content.title}`;
      break;
    case 'image':
      lastMsg = `[图片]`;
      break;
    case 'custom':
      lastMsg = resolveCustomMsgFormContent(content.dataType, content);
      break;
    case 'file':
      lastMsg = `[文件]`;
      break;
    case 'video':
      lastMsg = `[视频]`;
      break;
    case 'ding':
    case 'strong_reminder':
      let innerMsgType = content?.sourceContentType;
      if (typeof content?.sourceContentType === 'number') {
        innerMsgType = MsgTypeMap[content?.sourceContentType];
      }
      lastMsg = renderMsgBrief({ msgType: innerMsgType, msgContent: content.sourceMessageContent });
      break;
    case 'voice':
      lastMsg = `[语音]`;
      break;
    case 'robot':
      lastMsg = `[机器人]`;
      break;
    case 'face':
      lastMsg = <img src={content.iconUrl} alt="emoji" style={{width: '24px', height: '24px'}  } />;
      break;
    case 'merged':
      lastMsg = `[${content.msgTitle}]`;
      break;
    case 'location':
      lastMsg = `[位置] ${content.title}`;
      break;
    case 'rich_text':
      lastMsg = `[富文本] ${content.title}`;
      break;
    default:
      break;
  }

  return lastMsg;
}

export const resolveMsgFormContent = (msgType, content) => {
  let lastMsg = '';
  switch (msgType?.toLowerCase()) {
    case 'rtc':
      lastMsg = (content && content.rtcAction === 'invite') ? '发起实时音视频邀请' : '收到实时音视频邀请'
      break;
    case 'text':
      lastMsg = content.text || content.m;
      break;
    case 'url':
      lastMsg = `[链接]${content.title}`;
      break;
    case 'image':
      lastMsg = `[图片]`;
      break;
    case 'custom':
      lastMsg = resolveCustomMsgFormContent(content.dataType, content);
      break;
    case 'file':
      lastMsg = `[文件]`;
      break;
    case 'video':
      lastMsg = `[视频]`;
      break;
      case 'ding':
    case 'strong_reminder':
      lastMsg = `[提醒]`;
      break;
    case 'voice':
      lastMsg = `[语音]`;
      break;
    case 'robot':
      lastMsg = `[机器人]`;
      break;
    case 'face':
      lastMsg = <img src={content.iconUrl} alt="emoji" style={{width: '24px', height: '24px'}  } />;
      break;
    case 'merged':
      lastMsg = `[${content.msgTitle}]`;
      break;
    case 'location':
      lastMsg = `[位置] ${content.title}`;
      break;
    default:
      break;
  }
  return lastMsg;
}

export const diffPartWithArray = (list, filterlist, sameFunc) => {
  const diffpart: Array<any> = [];
  const samepart = list.filter(i => {
    const matchIndex = filterlist.findIndex(j => sameFunc(i, j) );
    if(matchIndex === -1) {
      diffpart.push(i);
      return false
    }
    return true;
  })

  return {
    diffpart,
    samepart
  }
}

export const transferFileSize = (size) => {
  const kbSize = Math.ceil(size/1024);
  if (kbSize < 1024) {
    return `${kbSize}KB`;
  } else {
    return `${Math.ceil(kbSize/1024)}MB`;
  }
}

export const sleep = (delay) => {
  if (typeof delay !== 'number') {
    return;
  }
  const start = +new Date();
  while(+new Date - start < delay) {
    continue;
  }
}

export const symbolEscape = (text) => {
  return text.replace(/[<>"&]/g, function(match, pos, originalText){
    switch(match){
      case "<": return "&lt;";
      case ">": return "&gt;";
      case "&": return "&amp;";
      case "\"": return "&quot;";
    }
  });
}

export const globalJump = (href) => {
  window.location.href = `${location.pathname}${location.search}${href}`;
}

export const isHideSomeFunctions = () => {
  // 直通车不要 消息搜索不要 钉消息不要 打标收藏不要
  // return location.href.indexOf('version=all') === -1;
  return false;
}
